<template>
  <a-card :bordered="false" title="附件信息">
    <a-button
      v-if="!defaultOptions.disabled"
      class="m-b-10"
      @click="handleUpload"
    ><a-icon type="upload" /> 附件上传
    </a-button>
    <a-config-provider>
      <template #renderEmpty>
        <a-empty :image="simpleImage">
          <p slot="description">您还没有上传附件 , 请上传附件, 附件大小不超过30M</p>
          <a-button @click="handleUpload" v-if="!defaultOptions.disabled">附件上传</a-button>
        </a-empty>
      </template>
      <a-form :form="form" :label-col="{ span: 0 }">
        <a-table
          ref="table"
          :columns="columns"
          :dataSource="fileData"
          :scroll="{ x: 1100, y: 300 }"
          :pagination="false"
          :rowKey="(record, index) => index"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="description" slot-scope="text">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </span>
          <div slot="category" slot-scope="text, record, i">
            <a-form-item v-if="defaultOptions.typeRequired && !defaultOptions.disabled">
              <a-select
                v-decorator="[
                  `type-${i}`,
                  { rules: [{ required: defaultOptions.typeRequired, message: '请选择文件分类!' }] },
                ]"
                placeholder="请选择文件分类"
                style="width: 160px"
                @change="(e) => handleChange(e, record.WJLJ)"
              >
                <a-select-option v-for="(item, index) in categoryList" :key="index" :value="item[fieldNames.value]">{{
                  item[fieldNames.label]
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <span v-else>{{ text || '/' }} </span>
          </div>
          <div slot="remark" slot-scope="text, record, j">
            <a-form-item v-if="!defaultOptions.disabled">
              <a-input
                v-decorator="[
                  `remark-${j}`,
                  { rules: [{ required: defaultOptions.remarkRequired, message: '请输入备注!', trigger: 'change' }] },
                ]"
                placeholder="输入备注"
                @change="handleChangeRemark($event, j)"
              ></a-input>
            </a-form-item>
            <ellipsis :length="32" v-else>{{ text || '/' }}</ellipsis>
          </div>
          <span slot="action" slot-scope="text, record, index">
            <template>
              <template v-if="record.isPreview">
                <a class="m-r-10" href="#" @click="handlePreview(record)">预览</a>
              </template>
              <template v-else>
                <a class="m-r-10" :href="baseUrl + record.WJLJ" target="_blank">下载</a>
              </template>
              <a-popconfirm
                title="您确定是否删除当前该文件?"
                ok-text="是"
                cancel-text="否"
                placement="left"
                @confirm="handleRemove(index)"
                v-if="!defaultOptions.disabled"
              >
                <a-icon slot="icon" type="question-circle-o" />
                <a href="#">删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
      </a-form>
    </a-config-provider>
    <upload-image :visible.sync="visible" @success="fileSuccess"></upload-image>
  </a-card>
</template>

<script>
import moment from 'moment'
import { Empty } from 'ant-design-vue'
import UploadImage from '@/components/UploadImage'
import { getDropdownList } from '@/api/common'
import { Ellipsis } from '@/components'
const columns = [
  {
    title: '序号',
    width: 80,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '文件名称',
    key: 'name',
    dataIndex: 'WJMC',
    scopedSlots: { customRender: 'description' },
    width: 200
  },
  {
    title: '文件类型',
    key: 'type',
    dataIndex: 'WJLX',
    width: 120
  },
  {
    title: '文件分类',
    key: 'category',
    dataIndex: 'CS_WJMC',
    scopedSlots: { customRender: 'category' },
    width: 170
  },
  {
    title: '备注',
    key: 'remark',
    dataIndex: 'WJSM',
    scopedSlots: { customRender: 'remark' },
    width: 200
  },
  {
    title: '状态',
    key: 'state',
    dataIndex: 'state',
    width: 120
  },
  {
    title: '操作',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  props: {
    // 用于获取文件下拉分类
    category: {
      type: String,
      default: ''
    },
    // 用于上传文件时 关联文件表名（需后台提供表名）
    tableNames: {
      type: String,
      default: ''
    },
    // 回显文件数据
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    fieldNames: {
      type: Object,
      default: () => ({
        label: 'DROPVALUE',
        value: 'DROPKEY'
      })
    },
    option: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    UploadImage,
    Ellipsis
  },
  data () {
    this.columns = columns
    return {
      visible: false,
      isFile: false,
      showViewer: false,
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      fileData: [],
      categoryList: [],
      form: this.$form.createForm(this, { name: 'fileList' }),
      defaultOptions: {
        typeRequired: true,
        remarkRequired: false,
        disabled: false
      }
    }
  },
  beforeCreate () {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
  },
  watch: {
    category: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          getDropdownList({ PmKey: newVal || '' }).then((res) => {
            this.categoryList = res.map((e) => {
              e[this.fieldNames.value] = e[this.fieldNames.value].toString()
              return e
            })
          })
        }
      },
      immediate: true
    },
    fileList: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          const { disabled, typeRequired } = this.defaultOptions
          this.fileData = newVal.map((e, index) => {
            if (!disabled) {
              const values = {}
              if (typeRequired) {
                values[`type-${index}`] = e.CS_WJLX
              }
              values[`remark-${index}`] = e.WJSM
              this.$nextTick(() => {
                this.form.setFieldsValue(values)
              })
            }
            return Object.assign(e, {
              state: '上传成功',
              isPreview: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'svg'].includes(e.WJLX)
            })
          })
        }
      },
      immediate: true
    },
    option: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          this.defaultOptions = Object.assign({}, this.defaultOptions, newVal)
        }
      },
      immediate: true
    }
  },
  methods: {
    handleUpload () {
      this.visible = true
    },
    handlePreview (record) {
      const imgList = []
      this.fileData.forEach((item) => {
        if (item.isPreview) {
          imgList.push(this.baseUrl + item.WJLJ)
        }
      })
      const imageIndex = imgList.findIndex((e) => e.indexOf(record.WJLJ) !== -1)
      this.$viewerApi({
        images: imgList,
        options: {
          initialViewIndex: imageIndex
        }
      })
    },
    handleChange (value, key) {
      const newData = [...this.fileData]
      // 通过文件路径去找到当前需要修改的行数据
      const target = newData.find((item) => key === item.WJLJ)
      // 通过选择的参数ID获取文件名称
      const rows = this.categoryList.find((item) => value === item[this.fieldNames.value])
      if (target) {
        // 赋值
        target.CS_WJLX = value
        target.CS_WJMC = rows[this.fieldNames.label]
        this.fileData = newData
      }
    },
    handleChangeRemark (e, index) {
      this.fileData[index].WJSM = e.target.value
    },
    /**
     * 文件上传成功回显数据方法
     * @description:
     * @param { String } ID 文件ID
     * @param { String } TID 表ID
     * @param { String } TNAME 文件上传关联表名（参数由后台提供）
     * @param { String } WJMC 文件名称
     * @param { String } WJLX 文件类型（eg: jpg/png/pdf/docx/excel/ppt/txt）
     * @param { String } WJLJ 文件路径（上传成功时返回的文件路径）
     * @param { String } WJSM 文件描述
     * @param { String } SCSJ 上传时间
     * @param { String } SCYH 上传用户
     * @param { String } Mode 状态（默认为0）
     * @param { String } CS_WJLX 参数文件类型（参数ID）
     * @param { String } CS_WJMC 参数文件名称
     * @param { String } PX 排序
     * @return { Object }
     */
    fileSuccess (result, file) {
      const fileList = []
      const fileType = file.name.replace(/.+\./, '') || ''
      let newResult = []
      result.forEach((item, index) => {
        fileList.push({
          ID: '',
          TID: '',
          TNAME: this.tableNames,
          WJMC: file.name,
          WJLJ: item,
          WJLX: fileType,
          WJSM: '',
          SCSJ: moment().format('YYYY-MM-DD'),
          SCYH: this.$store.getters.nickname,
          CS_WJLX: '',
          CS_WJMC: '',
          Mode: '0',
          PX: '',
          state: file.completed ? '上传成功' : '正在上传',
          isPreview: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'svg'].includes(fileType)
        })
      })
      newResult = this.fileData.concat(fileList)
      this.fileData = newResult
    },
    handleRemove (i) {
      const index = this.fileData.findIndex((key, j) => {
        return i === j
      })
      this.fileData.splice(index, 1)
    },
    validateFields (callback) {
      this.form.validateFields((err) => {
        callback(err, this.fileData)
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-form-item {
  margin-bottom: 0;
}
</style>
